# 如何通过按钮选择文件
import tkinter as tk
# 查看文件选择器
from tkinter.filedialog import askopenfilename
# 从PIL中导入ImageTk
from PIL import Image,ImageTk

class MyWindow():
    def __init__(self,app):
        self.app = app

        self.canvas = tk.Canvas(self.app,width=300,height=300,bg="white",relief="solid",borderwidth=1)
        self.canvas.pack()

        self.button = tk.Button(self.app,text="选择图片",command=self.openFile)
        self.button.pack()

    def openFile(self):
        self.v = tk.StringVar()
        self.v.set(askopenfilename())
        # 通过Entry编辑项模拟选取图片，并传递路径的过程
        image_path = tk.Entry(self.app,state="readonly",text=self.v).get()

        image = Image.open(image_path)
        image = image.resize((300,300))
        self.img_tk = ImageTk.PhotoImage(image)

        self.canvas.create_image(150,150,image=self.img_tk,anchor="center")

if __name__ == '__main__':
    app = tk.Tk()
    window = MyWindow(app)
    app.mainloop()